﻿using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Core.Utils;
using PMS.Data.DbUtils;
using PMS.Data.Entities.Localization;
using PMS.Services.Caching;
using PMS.Services.Caching.Extensions;
using PMS.Services.EntityServices.Stores;
using PMS.Services.Utils;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace PMS.Services.EntityServices.Localization
{
    /// <summary>
    /// Language service
    /// </summary>
    public partial class LanguageService : ILanguageService
    {
        #region Fields

        private readonly IStoreService _storeService;
        private readonly ICacheKeyService _cacheKeyService;
        private readonly IEventDispatcher _eventDispatcher;
        private readonly IRepository<Language> _languageRepository;

        #endregion

        #region Ctor

        public LanguageService(ICacheKeyService cacheKeyService,
            IStoreService storeService,
            IEventDispatcher eventDispatcher,
            IRepository<Language> languageRepository)
        {
            _storeService = storeService;
            _cacheKeyService = cacheKeyService;
            _eventDispatcher = eventDispatcher;
            _languageRepository = languageRepository;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Deletes a language
        /// </summary>
        /// <param name="language">Language</param>
        public virtual void DeleteLanguage(Language language)
        {
            if (language == null)
                throw new ArgumentNullException(nameof(language));

            var activeStores = _storeService.GetAllStores();
            if (activeStores.Any(store => store.DefaultLanguageId == language.Id))
                throw new PMSException($"{language.DisplayName} is being used by some stores, Change Stores default Language First! ", SystemLogLevel.Warning);
            
            _languageRepository.Delete(language);

            //event notification
            _eventDispatcher.EntityDeleted(language);
        }

        /// <summary>
        /// Gets all languages
        /// </summary>
        /// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Languages</returns>
        public virtual IList<Language> GetAllLanguages(bool showHidden = false, int storeId = 0)
        {
            var query = _languageRepository.Table;
            if (!showHidden) query = query.Where(l => l.IsActive);
            query = query.OrderBy(l => l.DisplayOrder).ThenBy(l => l.Id);

            //cacheable copy
            var key = _cacheKeyService.PrepareKeyForDefaultCache(CacheKeyConfigs.LanguagesAllCacheKey, storeId, showHidden);
            return query.ToCachedList(key);
        }

        /// <summary>
        /// Gets a language
        /// </summary>
        /// <param name="languageId">Language identifier</param>
        /// <returns>Language</returns>
        public virtual Language GetLanguageById(int languageId)
        {
            if (languageId == 0)
                return null;

            return _languageRepository.ToCachedGetById(languageId);
        }

        /// <summary>
        /// Inserts a language
        /// </summary>
        /// <param name="language">Language</param>
        public virtual void InsertLanguage(Language language)
        {
            if (language == null)
                throw new ArgumentNullException(nameof(language));

            _languageRepository.Insert(language);

            //event notification
            _eventDispatcher.EntityInserted(language);
        }

        /// <summary>
        /// Updates a language
        /// </summary>
        /// <param name="language">Language</param>
        public virtual void UpdateLanguage(Language language)
        {
            if (language == null)
                throw new ArgumentNullException(nameof(language));

            //update language
            _languageRepository.Update(language);

            //event notification
            _eventDispatcher.EntityUpdated(language);
        }

        /// <summary>
        /// Get 2 letter ISO language code
        /// </summary>
        /// <param name="language">Language</param>
        /// <returns>ISO language code</returns>
        public virtual string GetTwoLetterIsoLanguageName(Language language)
        {
            if (language == null)
                throw new ArgumentNullException(nameof(language));

            if (string.IsNullOrEmpty(language.LanguageCode))
                return "cn";

            var culture = new CultureInfo(language.CultureCode);
            var code = culture.TwoLetterISOLanguageName;

            return string.IsNullOrEmpty(code) ? "en" : code;
        }

        #endregion
    }
}
